package com.wayne.structure.array;

/**
 * Find the smallest and second smallest elements in an array
 *
 * Example:
 * Input:  arr[] = {12, 13, 1, 10, 34, 1}
 * Output: The smallest element is 1 and second Smallest element is 10
 *
 */

public class ArrayTest1 {

    private static void operation(Integer[] source) {
        //思路1:先排序再取出来前两个元素

        //思路2:两次遍历分别取出最小的和第二小的元素

        //思路3:一次遍历一次性取出最小的和第二小的
        Integer first = source[0];
        Integer second = source[1];
        //TODO 不用中间参数交换 a,b 的值
        //方法一
//        if (first > second) {
//            first = first + second;
//            second = first - second;
//            first = first - second;
//        }

        //方法二   ^与运算  相同为0 不同为1   1^1=0; 0^0=0; 0^1=1
        if (first > second) {
            first = first ^ second;
            second = first ^ second;
            first = first ^ second;
        }


        for (int i=2; i<source.length; i++) {
            if (source[i] < first) {
                second = first;
                first = source[i];
            } else if (source[i] > first && source[i] < second) {
                second = source[i];
            }
        }

        System.out.println("The smallest element is " + first
                +" and second Smallest element is " + second);
    }


    public static void main(String[] args) {
        Integer[] sourceArray = {100, 12, 13, 1, 10, 34, 1};
        operation(sourceArray);
    }

}
